package org.jeecg.modules.basedata.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.entity.basedata.*;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.entity.charge.ChargeGenerateBills;
import org.jeecg.enums.base.BaseRentContractEnum;
import org.jeecg.modules.basedata.service.*;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.service.IFeignChargeService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 租赁合同
 * @Author: liurui
 * @Date:   2021-06-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags="租赁合同")
@RestController
@RequestMapping("/b/basedata/rentContract")
public class RentContractController {
	@Autowired
	private IRentContractService rentContractService;
	@Autowired
    private ISysUserRoleService sysUserRoleService;
	@Autowired
	private IBaseProjectService baseProjectService;
	@Autowired
	private IBaseFloorService baseFloorService;
	@Autowired
	private IBaseRoomService baseRoomService;
	@Autowired
	private IFeignChargeService feignChargeService;
	@Autowired
	private IBaseFeeRuleContractService baseFeeRuleContractService;

	/**
	  * 分页列表查询
	 * @param rentContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "租赁合同-分页列表查询")
	@ApiOperation(value="租赁合同-分页列表查询", notes="租赁合同-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<RentContract>> queryPageList(RentContract rentContract,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<RentContract>> result = new Result<IPage<RentContract>>();
		rentContract.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",rentContract.getMenuPath(),null,rentContract.getDepartIdEx()));
		Page<RentContract> page = new Page<RentContract>(pageNo, pageSize);
		page.setRecords(rentContractService.findPage(page,rentContract));
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}



	@AutoLog(value = "合同管理--合同终止")
	@ApiOperation(value="合同管理--合同终止", notes="合同管理--合同终止")
	@RequestMapping(value = "/contractStop")
	public Result<String> contractStop(RentContract rentContract) {
		try {
			RentContract contract = rentContractService.getById(rentContract.getId());
			if (contract == null){
				return Result.error("未查询到当前合同信息");
			}
			List<ChargeBills> chargeBills = feignChargeService.queryContractAllBills(contract.getId(),null,  SsoUtil.getLoginUser().getTenantId());
			//房间未生成账单
			if (chargeBills == null || chargeBills.size() <= 0){
				contract.setEndDate(new Date());
				//修改到期时间为当前时间
				rentContractService.updateById(contract);
				return Result.ok();
			}
			//判断当前月份是否缴费
			String sdf = new SimpleDateFormat("YYYY-MM").format(new Date());
			for (ChargeBills bills : chargeBills){
				//已生成当前作废月份账单 && 已经缴费
				if (bills.getZjCny().equals(sdf) && bills.getZjSkrq() != null){
					return Result.ok("["+ sdf +"]账单已经缴费，无法作废，请退款后再作废");
				}
			}
			List<ChargeBills> bills = feignChargeService.queryContractAllBills(contract.getId(),sdf,  SsoUtil.getLoginUser().getTenantId());
			//无未交账单
			if (bills == null || bills.size() <= 0){
				contract.setEndDate(new Date());
				//修改到期时间为当前时间
				rentContractService.updateById(contract);
				return Result.ok();
			}
			List<String> ids = bills.stream().map(ChargeBills::getId).collect(Collectors.toList());
			feignChargeService.batchBillDelete(ids, SsoUtil.getLoginUser().getTenantId());
			contract.setEndDate(new Date());
			//修改到期时间为当前时间
			rentContractService.updateById(contract);
		}catch (Exception e){
			log.error(e.getMessage(),e);
			Result.error("操作失败");
		}
		return Result.ok();
	}


	/**
	 *   生成账单
	 * @param
	 * @return
	 */
	@AutoLog(value = "合同管理--生成应收账单")
	@ApiOperation(value="合同管理--生成应收账单", notes="合同管理--生成应收账单")
	@RequestMapping(value = "/generateContractBills")
	public Result<String> generateContractBills(@RequestBody ChargeGenerateBills chargeGenerateBills) {
		log.info("合同管理--生成账单接受参数:{}",chargeGenerateBills);
		if (StringUtils.isBlank(chargeGenerateBills.getFeeRuleId())){
			return Result.error("请选择收费标准!");
		}
		if (chargeGenerateBills.getContractIds() == null || chargeGenerateBills.getContractIds().size() <= 0){
			return Result.error("请选择生成的合同!");
		}
		return feignChargeService.createChargeBillsContractNew(chargeGenerateBills, SsoUtil.getLoginUser().getTenantId());
	}
	/*public Result<List<ChargeBills>> generateContractBills(@RequestParam("contractId")String contractId) {
		Result<List<ChargeBills>> chargeBillsResult = new Result<>();
		String tenantId = SsoUtil.getLoginUser().getTenantId();
		//获取房间所有收费项
		List<String> contractIds= com.beust.jcommander.internal.Lists.newArrayList() ;
		contractIds.add(contractId);
		List<String> ruleId = baseFeeRuleContractService.getAllFeeItemId(contractId);
		ChargeGenerateBills chargeGenerateBills = new ChargeGenerateBills();
		chargeGenerateBills.setContractIds(contractIds);
		String join = Joiner.on(",").join(ruleId);
		chargeGenerateBills.setFeeRuleId(join);
		if(ruleId.size() > 0 ){
			try {
				//调用生成账单方法
				feignChargeService.createChargeBillsContractNew(chargeGenerateBills,tenantId);
				//获取房间未支付信息
				List<ChargeBills> chargeBills = feignChargeService.queryContractBills(contractId,tenantId);
				chargeBillsResult.setResult(chargeBills);
				chargeBillsResult.setSuccess(true);
				chargeBillsResult.setMessage("账单已生成");
			}catch (Exception e) {
				log.info("错误信息", e.fillInStackTrace());
				return chargeBillsResult.error500("系统错误");
			}
		}
		return chargeBillsResult;
	}*/
	
	/**
	  *   添加
	 * @param rentContract
	 * @return
	 */
	@AutoLog(value = "租赁合同-添加")
	@ApiOperation(value="租赁合同-添加", notes="租赁合同-添加")
	@PostMapping(value = "/add")
	public Result<RentContract> add(@RequestBody RentContract rentContract) {
		Result<RentContract> result = new Result<RentContract>();
		try {
			return rentContractService.saveRentContract(rentContract);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	 /**
	  * 获取项目下的房间
	  */
	 @RequestMapping("getAllContractList")
	 public Result<IPage<RentContract>> getAllContractList(@RequestParam("projectId")String projectId,
												@RequestParam(value = "feeRuleId",required = false) String feeRuleId,
												@RequestParam(value = "roomId",required = false)String roomId,
												@RequestParam(value = "floorId",required = false)String floorId,
												@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
		 Result<IPage<RentContract>> result = new Result<IPage<RentContract>>();
		 Page<RentContract> pageList = new Page<RentContract>(pageNo, pageSize);
		 pageList = rentContractService.getContractList(pageList,projectId,feeRuleId,roomId,floorId);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }

	 /**
	  * 合同收费项
	  */
	 @RequestMapping("/queryContractFeeList")
	 public Result<IPage<RentContract>> queryContractFeeList(RentContract rentContract,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req){
		 Result<IPage<RentContract>> result = new Result<IPage<RentContract>>();
		 try {
			 Page<RentContract> pageList = new Page<RentContract>(pageNo, pageSize);
			 pageList = rentContractService.queryContractFeeList(pageList,rentContract);
			 result.setSuccess(true);
			 result.setResult(pageList);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("查询失败！");
		 }
		 return result;
	 }
	
	/**
	  *  编辑
	 * @param rentContract
	 * @return
	 */
	@AutoLog(value = "租赁合同-编辑")
	@ApiOperation(value="租赁合同-编辑", notes="租赁合同-编辑")
	@PutMapping(value = "/edit")
	public Result<RentContract> edit(@RequestBody RentContract rentContract) {
		return rentContractService.updateRentContract(rentContract);
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "租赁合同-通过id删除")
	@ApiOperation(value="租赁合同-通过id删除", notes="租赁合同-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			return rentContractService.delRentContract(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "租赁合同-批量删除")
	@ApiOperation(value="租赁合同-批量删除", notes="租赁合同-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<RentContract> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<RentContract> result = new Result<RentContract>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.rentContractService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "租赁合同-通过id查询")
	@ApiOperation(value="租赁合同-通过id查询", notes="租赁合同-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<RentContract> queryById(@RequestParam(name="id",required=true) String id) {
		Result<RentContract> result = new Result<RentContract>();
		RentContract rentContract = rentContractService.getById(id);
		if(rentContract==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(rentContract);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<RentContract> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              RentContract rentContract = JSON.parseObject(deString, RentContract.class);
              queryWrapper = QueryGenerator.initQueryWrapper(rentContract, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      LoginUser loginUser =  SsoUtil.getLoginUser();
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<RentContract> pageList = rentContractService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "租赁合同列表");
      mv.addObject(NormalExcelConstants.CLASS, RentContract.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("租赁合同列表数据", "导出人:" + loginUser.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<RentContract> listRentContracts = ExcelImportUtil.importExcel(file.getInputStream(), RentContract.class, params);
              rentContractService.saveBatch(listRentContracts);
              return Result.ok("文件导入成功！数据行数:" + listRentContracts.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

	/**
	 * 通过excel导入合同数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importRentContractExcel", method = RequestMethod.POST)
	public Result<?> importRentContractExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			int titleRow = 0;
			params.setTitleRows(titleRow);
			params.setHeadRows(titleRow);
			params.setNeedSave(true);
			try {
				List<BaseRentContractExcel> rentContractExcelList = ExcelImportUtil.importExcel(file.getInputStream(), BaseRentContractExcel.class, params);
				if(rentContractExcelList.size() <= 0){
					return Result.error("文件内容为空，导入失败!");
				}
				//禁止同一房间一次性做多种操作
				Set<String> setPrimary = new HashSet<>();
				for (BaseRentContractExcel excel : rentContractExcelList){
					setPrimary.add(excel.getFloorName()+excel.getRoomName());
				}
				if (setPrimary.size() != rentContractExcelList.size()){
					return Result.error("同一楼宇同一房间不允许一次性导入多条数据，导入失败！");
				}
				List<String> codeList = rentContractExcelList.stream().map(m -> StrUtil.trim(m.getCode())).distinct().collect(Collectors.toList());
				if (codeList.size() !=  rentContractExcelList.size()) {
					return Result.error("导入合同编号不能相同，导入失败！");
				}
				StringBuilder failureMsg = new StringBuilder();
				int failureNum = 0;
				List<RentContract> rentContractsList = Lists.newArrayList();
				for (BaseRentContractExcel rentContractExcel: rentContractExcelList){
					titleRow++;
					if (StringUtils.isBlank(rentContractExcel.getProjectName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
						failureNum++;
						continue;
					}
					BaseProject baseProject = baseProjectService.getProjectByName(rentContractExcel.getProjectName());
					if (baseProject == null) {
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称系统中不存在; ");
						failureNum++;
						continue;
					}
					if (StringUtils.isBlank(rentContractExcel.getFloorName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入楼宇名称; ");
						failureNum++;
						continue;
					}
					BaseFloor baseFloor = baseFloorService.queryFloorName(baseProject.getId(), rentContractExcel.getFloorName());
					if (baseFloor == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的楼宇名称系统中不存在; ");
						failureNum++;
						continue;
					}
					if (StringUtils.isBlank(rentContractExcel.getRoomName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间名称; ");
						failureNum++;
						continue;
					}
					BaseRoom br = baseRoomService.getBaseRoomByName(rentContractExcel.getRoomName(), baseFloor.getId());
					if (br == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的房间名称必须在系统中存在; ");
						failureNum++;
						continue;
					}
					//租赁人
					if (StringUtils.isBlank(rentContractExcel.getCustomer())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入租赁人; ");
						failureNum++;
						continue;
					}
					//合同编号
					if (StringUtils.isBlank(rentContractExcel.getCode())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同编号; ");
						failureNum++;
						continue;
					} else {
                        RentContract contract = new RentContract();
                        contract.setCode(rentContractExcel.getCode());
						List<RentContract> rentContract = rentContractService.selectByRentContract(contract);
						if (rentContract.size() >= 1) {
							failureMsg.append("<br/>第").append(titleRow).append("行：合同编号在系统中已存在,请修改后重新上传; ");
							failureNum++;
							continue;
						}
					}
					//合同名称

					//合同起始日期
					if (rentContractExcel.getStartDate() == null) {
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同起始日期; ");
						failureNum++;
						continue;
					}
					//合同截止日期
					if (rentContractExcel.getEndDate() == null) {
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同截止日期; ");
						failureNum++;
						continue;
					}
					//合同原件

					//合同状态
					if (rentContractExcel.getStatusName() == null) {
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同状态; ");
						failureNum++;
						continue;
					} else {
						rentContractExcel.setStatus(BaseRentContractEnum.getValue(rentContractExcel.getStatusName()));
					}

					//备注
					String roomId = String.valueOf(IdWorker.getId());
					rentContractExcel.setProjectId(baseProject.getId());
					rentContractExcel.setFloorId(baseFloor.getId());
					BaseRoom room = new BaseRoom();
					BeanUtils.copyProperties(rentContractExcel, room);
					RentContract rentContract = new RentContract();
					BeanUtils.copyProperties(rentContractExcel, rentContract);
					rentContract.setRoomId(br.getId());
					//创建人
					rentContract.setCreateBy(SsoUtil.getLoginUser().getId());
					//创建时间
					rentContract.setCreateTime(DateUtil.date());
					rentContractsList.add(rentContract);
				}
				if (failureNum > 0){
					return Result.error("文件导入失败:" + failureMsg.toString());
				}
				rentContractService.saveBatch(rentContractsList);
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入成功！");
	}

}
